package com.rbac.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.admin.entity.SysMenu;
import com.rbac.admin.mapper.SysMenuMapper;
import com.rbac.admin.service.CacheService;
import com.rbac.admin.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单服务实现类
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private CacheService cacheService;
    
    @Value("${cache.expiration.menu}")
    private long menuCacheExpiration;
    
    // 缓存key前缀
    private static final String MENU_TREE_CACHE_KEY = "menu:tree";
    private static final String MENU_USER_CACHE_KEY = "menu:user:";
    private static final String MENU_ROLE_CACHE_KEY = "menu:role:";

    @Override
    public List<SysMenu> getMenuTree() {
        // 尝试从缓存获取
        List<SysMenu> menuTree = cacheService.get(MENU_TREE_CACHE_KEY);
        if (menuTree != null) {
            return menuTree;
        }
        
        // 缓存未命中，查询数据库
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(SysMenu::getSortOrder);
        List<SysMenu> menuList = list(queryWrapper);
        
        // 构建树形结构
        menuTree = buildMenuTree(menuList);
        
        // 存入缓存
        cacheService.set(MENU_TREE_CACHE_KEY, menuTree, menuCacheExpiration);
        
        return menuTree;
    }

    @Override
    public List<SysMenu> getMenuTreeByUserId(Long userId) {
        // 尝试从缓存获取
        String cacheKey = MENU_USER_CACHE_KEY + userId;
        List<SysMenu> menuTree = cacheService.get(cacheKey);
        if (menuTree != null) {
            return menuTree;
        }
        
        // 缓存未命中，查询数据库
        List<SysMenu> menuList = baseMapper.selectMenusByUserId(userId);
        
        // 构建树形结构
        menuTree = buildMenuTree(menuList);
        
        // 存入缓存
        cacheService.set(cacheKey, menuTree, menuCacheExpiration);
        
        return menuTree;
    }

    @Override
    public List<SysMenu> getMenuTreeByRoleId(Long roleId) {
        // 尝试从缓存获取
        String cacheKey = MENU_ROLE_CACHE_KEY + roleId;
        List<SysMenu> menuTree = cacheService.get(cacheKey);
        if (menuTree != null) {
            return menuTree;
        }
        
        // 缓存未命中，查询数据库
        List<SysMenu> menuList = baseMapper.selectMenusByRoleId(roleId);

        // 构建树形结构
        menuTree = buildMenuTree(menuList);
        
        // 存入缓存
        cacheService.set(cacheKey, menuTree, menuCacheExpiration);
        
        return menuTree;
    }

    /**
     * 构建菜单树形结构
     * @param menuList 菜单列表
     * @return 树形菜单
     */
    private List<SysMenu> buildMenuTree(List<SysMenu> menuList) {
        // 将菜单列表转换为Map，方便查找
        Map<Long, SysMenu> menuMap = menuList.stream().collect(Collectors.toMap(SysMenu::getId, menu -> menu));
        
        // 构建树形结构
        List<SysMenu> result = new ArrayList<>();
        for (SysMenu menu : menuList) {
            // 如果是顶级菜单，直接添加到结果集
            if (menu.getParentId() == 0) {
                result.add(menu);
            } else {
                // 如果不是顶级菜单，找到其父菜单并添加到children中
                SysMenu parentMenu = menuMap.get(menu.getParentId());
                if (parentMenu != null) {
                    if (parentMenu.getChildren() == null) {
                        parentMenu.setChildren(new ArrayList<>());
                    }
                    parentMenu.getChildren().add(menu);
                }
            }
        }
        
        return result;
    }
}